package cn.wgx.common.security.client.config;

import cn.wgx.common.security.client.config.tokenstore.RedisTemplateTokenStore;
import cn.wgx.common.security.client.config.tokenstore.ResJwtAccessTokenConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.util.Assert;

import javax.sql.DataSource;

@Configuration
public class TokenStoreConfig {

    /**
     * redis存储token信息
     *
     * @param connectionFactory
     * @return
     */
    @Bean("tokenStore")
    @ConditionalOnProperty(prefix = "security.oauth2.token.store", name = "type", havingValue = "redis", matchIfMissing = true)
    public RedisTemplateTokenStore redisTokenStore(RedisConnectionFactory connectionFactory) {
//		return new RedisTokenStore( redisTemplate.getConnectionFactory() ) ; //单台redis服务器
        Assert.state(connectionFactory != null, "connectionFactory must be provided");
        RedisTemplateTokenStore redisTemplateStore = new RedisTemplateTokenStore(connectionFactory);
        return redisTemplateStore;
    }


    /**
     * 数据库存储token信息
     *
     * @param dataSource
     * @return
     */
    @Bean
    @ConditionalOnProperty(prefix = "security.oauth2.token.store", name = "type", havingValue = "jdbc", matchIfMissing = false)
    public JdbcTokenStore jdbcTokenStore(DataSource dataSource) {
//		oauth_access_token, oauth_refresh_token 创建两张表
        return new JdbcTokenStore(dataSource);

    }

    //使用jwt替换原有的uuid生成token方式
    @Configuration
    @ConditionalOnProperty(prefix = "security.oauth2.token.store", name = "type", havingValue = "jwt", matchIfMissing = false)
    public static class JWTTokenConfig {
        @Bean
        public JwtTokenStore jwtTokenStore() {
            return new JwtTokenStore(jwtAccessTokenConverter());
        }

        @Bean
        public JwtAccessTokenConverter jwtAccessTokenConverter() {
            JwtAccessTokenConverter accessTokenConverter = new ResJwtAccessTokenConverter();
            accessTokenConverter.setSigningKey("ocp");
            return accessTokenConverter;
        }
    }

}
